//! 安全的事件分发器实现
//! 使用标准库集合避免内存管理问题

use crate::event::{DynamicEvent, DynamicEventHandler/*, EventResult*/};

use std::sync::{Arc, RwLock, Mutex};
use std::collections::VecDeque;
use fxhash::FxHashMap;
use std::thread;
use std::time::Duration;
use std::sync::atomic::{AtomicBool, Ordering};

/// 安全分发器配置
#[derive(Debug, Clone)]
pub struct SafeDispatcherConfig {
    pub worker_count: usize,
}

impl Default for SafeDispatcherConfig {
    fn default() -> Self {
        Self {
            worker_count: 2,
        }
    }
}

/// 安全的事件分发器 - 使用标准库避免内存问题
pub struct SafeEventDispatcher {
    config: SafeDispatcherConfig,
    event_queue: Arc<Mutex<VecDeque<DynamicEvent>>>,
    handlers: Arc<RwLock<FxHashMap<String, Vec<Arc<dyn DynamicEventHandler>>>>>,
    running: Arc<AtomicBool>,
    worker_handles: Vec<thread::JoinHandle<()>>,
}

/// 安全的发送器
#[derive(Clone)]
pub struct SafeEventSender {
    event_queue: Arc<Mutex<VecDeque<DynamicEvent>>>,
}

impl SafeEventSender {
    pub fn publish(&self, event: DynamicEvent) -> Result<(), DynamicEvent> {
        // 使用阻塞锁确保事件不会丢失
        let mut queue = self.event_queue.lock().unwrap();
        queue.push_back(event);
        Ok(())
    }
}

impl SafeEventDispatcher {
    pub fn new(config: SafeDispatcherConfig) -> Self {
        Self {
            config,
            event_queue: Arc::new(Mutex::new(VecDeque::new())),
            handlers: Arc::new(RwLock::new(FxHashMap::default())),
            running: Arc::new(AtomicBool::new(false)),
            worker_handles: Vec::new(),
        }
    }

    pub fn register_handler(&mut self, event_type: &str, handler: Arc<dyn DynamicEventHandler>) {
        let mut handlers = self.handlers.write().unwrap();
        handlers.entry(event_type.to_string())
            .or_insert_with(Vec::new)
            .push(handler);
    }

    pub fn clone_sender(&self) -> SafeEventSender {
        SafeEventSender {
            event_queue: self.event_queue.clone(),
        }
    }

    pub fn start(&mut self) {
        if self.running.load(Ordering::Relaxed) {
            return;
        }

        self.running.store(true, Ordering::Relaxed);

        for worker_id in 0..self.config.worker_count {
            let running = self.running.clone();
            let event_queue = self.event_queue.clone();
            let handlers = self.handlers.clone();

            let handle = thread::Builder::new()
                .name(format!("safe-worker-{}", worker_id))
                .spawn(move || {
                    while running.load(Ordering::Relaxed) {
                        let event_opt = {
                            if let Ok(mut queue) = event_queue.try_lock() {
                                queue.pop_front()
                            } else {
                                None
                            }
                        };

                        if let Some(event) = event_opt {
                            let event_type = event.event_type();
                            
                            if let Ok(handlers_guard) = handlers.read() {
                                if let Some(handler_list) = handlers_guard.get(event_type) {
                                    for handler in handler_list {
                                        let _result = handler.handle_dynamic(&event);
                                        // 简化处理：只处理第一个匹配的handler
                                        break;
                                    }
                                }
                            }
                        } else {
                            thread::sleep(Duration::from_millis(1));
                        }
                    }
                })
                .expect("Failed to spawn worker thread");

            self.worker_handles.push(handle);
        }
    }

    pub fn stop(&mut self) {
        self.running.store(false, Ordering::Relaxed);
        
        while let Some(handle) = self.worker_handles.pop() {
            let _ = handle.join();
        }
    }

    pub fn publish(&self, event: DynamicEvent) -> Result<(), DynamicEvent> {
        // 使用阻塞锁确保事件不会丢失
        let mut queue = self.event_queue.lock().unwrap();
        queue.push_back(event);
        Ok(())
    }
}